<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span='7'>
          <el-input placeholder="请输入内容" clearable v-model="FormData.query" class="input-with-select" @clear='getData()'>
            <el-button slot="append" icon="el-icon-search" @click='search'></el-button>
          </el-input>
        </el-col>
        <el-col :span='4'>
          <el-button class='add-button' type="primary" icon="el-icon-search" @click='addUser'>添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="TableData" style="width: 100%">
        <el-table-column type='index' prop='#'></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column label="状态" width="180">
          <template #default='scope'>
            <el-switch
              v-model="scope.row.mg_state"
              @change='changeStatu(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column  label="操作" width="180">
          <template #default='scope'>
            <el-button type="primary" size='mini' icon="el-icon-edit" @click='changeShow(scope.row.id)'></el-button>
            <el-button type="danger" size='mini' icon="el-icon-delete" @click='deleteUser(scope.row.id)'></el-button>
            <el-tooltip class="item" effect="dark" content="角色分配" placement="top" :enterable='false'>
              <el-button type="warning" size='mini' icon="el-icon-setting" @click='setting( scope.row )'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page='FormData.pagenum'
        :page-sizes="[5, 20, 30, 40]"
        :page-size="FormData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close='handleClose'>
      <el-form :model="addFormData" :rules="addFormData_rules" ref="addForm_ref" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFormData.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserSbmit">添 加</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="changeDialog"
      width="50%"
      @close='changeDialogClose'>
      <el-form :model="changeFormData" :rules="changeFormData_rules" ref="changeFormData_ref" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="changeFormData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="changeFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialog = false">取 消</el-button>
        <el-button type="primary" @click="changeUsersSbmit">修 改</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="settingDialog"
      width="50%">
      <div>
        <div>当前用户：<span>{{ settingItem.username }}</span></div>
        <div>当前角色：<span>{{ settingItem.role_name }}</span></div>
        <span>选择角色：</span><el-select v-model="selectRoles" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingDialog = false">取 消</el-button>
        <el-button type="primary" @click="settingSbmit">分 配</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let validateEmail = (rule, value, callback) => {
      if( value === '' ) callback()
      const zz = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if ( zz.test(value) ) callback()
      else callback(new Error('请输入合法的邮箱'))
    }
    let validateMobile = (rule, value, callback) => {
      if( value === '' ) callback()
      const zz = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if ( zz.test(value) ) return callback()
      else return callback(new Error('请输入合法的手机号'))
    }
    return {
      TableData:[],
      FormData:{
        query:'',
        pagesize:5,
        pagenum:1
      },
      total:0,
      dialogVisible:false,
      changeDialog:false,
      settingDialog:false,
      addFormData: {
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      changeFormData: {
        username:'',
        email:'',
        mobile:''
      },
      changeFormData_rules: {
        email:[ {validator:validateEmail, trigger: 'blur' }],
        mobile:[ {validator:validateMobile, trigger: 'blur' }]
      },
      addFormData_rules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }],
        email:[ {validator:validateEmail, trigger: 'blur' }],
        mobile:[ {validator:validateMobile, trigger: 'blur' }]
      },
      settingItem:{},
      rolesList:[],
      selectRoles:''
    }
  },
  methods:{
    async getData() {
      let res = await this.axios.get('/users', { params: this.FormData })
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.TableData = res.data.users
      this.total = res.data.total
    },
    search() {
      this.FormData.pagenum = 1
      this.getData()
    },
    handleSizeChange( size ) {
      this.FormData.pagesize = size
      this.getData()
    },
    handleCurrentChange( num ) {
      this.FormData.pagenum = num
      this.getData()
    },
    addUser() {
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs.addForm_ref.resetFields()
    },
    async addUserSbmit() {
      let rel = await this.$refs.addForm_ref.validate().catch( err=>err )
      if( !rel ) return this.pop.error('请正确填写')
      let res = await this.axios.post('/users', this.addFormData)
      if( res.meta.status !== 201 ) return this.pop.error( res.meta.msg )
      this.pop.success( res.meta.msg )
      this.getData()
      this.dialogVisible = false
    },
    async changeStatu(row) {
      let res = await this.axios.put(`users/${ row.id }/state/${ row.mg_state }`)
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.pop.success( res.meta.msg )
    },
    changeDialogClose() {
      this.changeDialog = false
      this.$refs.changeFormData_ref.resetFields()
    },
    async changeUsersSbmit() {
      let rel = await this.$refs.changeFormData_ref.validate().catch( err=>err )
      if( !rel ) return this.pop.error('请正确填写')
      let res = await this.axios.put(`users/${ this.changeFormData.id }`, this.changeFormData )
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.pop.success( res.meta.msg )
      this.changeDialog = false
    },
    async changeShow( id ) {
      let res = await this.axios.get( `users/${ id }` )
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.changeFormData = res.data
      this.changeDialog = true

    },
    async deleteUser( id ) {
      let rel  = await this.confirm('永久删除该用户', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch( err=>err )
      if( rel !== 'confirm' ) return;
      let res = await this.axios.delete(`users/${ id }`)
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.pop.success( res.meta.msg )
      this.getData()
    },
    async setting (row) {
      this.settingItem = row
      let res = await this.axios.get('roles')
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.rolesList = res.data
      this.settingDialog = true

    },
    async settingSbmit() {
      if( this.selectRoles === '' ) return this.pop.error('请选择角色')
      let res = await this.axios.put(`users/${ this.settingItem.id }/role`, { rid: this.selectRoles })
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.pop.success( res.meta.msg )
      this.getData()
      this.settingDialog = false
    }
  },
  created() {
    this.getData()
  }
}
</script>

<style scoped>
  .add-button {
    margin-left:25px;
  }
</style>